var WXBizDataCrypt = require('../../utils/WXBizDataCrypt');
class UserInfo {
    /**
     * 获取用户个人主页信息
     * @api {GET}         /user/info          获取用户个人主页信息
     * @apiName           /user/info
     * @apiGroup          User
     * @apiVersion 0.1.0
     * @apiSuccessExample Success-Response:
     * {
        "code": 0,
        "msg": "success",
        "data": {
            "leftDay": 365, //剩余天数
            "limit": 0, //次卡
        }
      }
     */
    async info(ctx) {
        let {
            db,
            user: { User }
        } = ctx;

        let condition = {
            where: {
                id: User.id
            },
            attributes: ['leftDay', 'limit', 'reward']
        };
        let data = await db.User.findOne(condition);
        ctx.success({ leftDay: data.leftDay, limit: data.limit + data.reward });
    }
    /**
     * 获取用户使用记录
     * @api {GET}         /user/use          获取用户使用记录
     * @apiName           /user/use
     * @apiGroup          User
     * @apiVersion 0.1.0
     * @apiParam          {Int}            page        页数
     * @apiParam          {Int}            type=0      类型（0为使用记录,1为购买记录）
     * @apiSuccessExample Success-Response:
     * {
        "code": 0,
        "msg": "success",
        "data": [
            {
                "deviceId": 2,
                "address": "四川省成都市高新区天府大道一段8号",
                "amount": "29.99",
                "payment": "会员抵扣"
            }
        ]
      }
     */
    async use(ctx) {
        let {
            db,
            user: { User },
            request: {
                query: { page = 1, type = 0 }
            }
        } = ctx;

        page = parseInt(page);
        type = parseInt(type);
        let data;
        if (type === 0) {
            let condition = {
                limit: 10,
                offset: (page - 1) * 10,
                where: {
                    userId: User.id
                },
                order: [['id', 'DESC']],
                attributes: [
                    'deviceId',
                    'address',
                    'amount',
                    'payment',
                    'createdAt'
                ]
            };
            data = await db.Use.findAll(condition);
        } else {
            let condition = {
                limit: 10,
                offset: (page - 1) * 10,
                where: {
                    userId: User.id
                },
                order: [['id', 'DESC']],
                attributes: ['type', 'price', 'createdAt']
            };
            data = await db.Buy.findAll(condition);
        }
        ctx.success(data);
    }
    /**
     * 常见问题
     * @api {GET}         /user/question          常见问题
     * @apiName           /user/question
     * @apiGroup          User
     * @apiVersion 0.1.0
     * @apiParam          {Int}            page        页数
     * @apiSuccessExample Success-Response:
     * {
        "code": 0,
        "msg": "success",
        "data": [
            {
                "id": 1,
                "question": "无法扫码洗车",
                "answer": "请确保，在网络信号通讯正常的情况下，进行扫码洗车。",
                "createdAt": "2019-06-05T09:18:33.000Z",
                "updatedAt": "2019-06-05T09:18:35.000Z"
            }
        ]
      }
     */
    async question(ctx) {
        let {
            db,
            request: {
                query: { page = 1 }
            }
        } = ctx;

        page = parseInt(page);

        let condition = {
            limit: 10,
            offset: (page - 1) * 10
        };
        let data = await db.Question.findAll(condition);
        ctx.success(data);
    }
    /**
     * 绑定手机号
     * @api {POST}        /user/phone         绑定手机号
     * @apiName           /user/phone
     * @apiGroup          User
     * @apiParam          {String}            iv                   iv
     * @apiParam          {String}            encryptedData        encryptedData
     * @apiVersion 0.1.0
     * @apiSuccessExample Success-Response:
     * {
        "code": 0,
        "msg": "success",
        "data": {
           "phone": 17726376713
         }
       }
     */
    async phone(ctx) {
        let {
            db,
            user: { User },
            request: {
                body: { iv, encryptedData }
            }
        } = ctx;

        let appId = 'wx7cd2a45df18747f6';
        let sessionKey;
        const user = await db.User.findOne({ where: { id: User.id } });

        if (!user) {
            ctx.errors('服务器错误');
            return;
        }
        sessionKey = user.sessionKey;

        var pc = new WXBizDataCrypt(appId, sessionKey);

        var data = pc.decryptData(encryptedData, iv);

        user.phone = data.phoneNumber;
        user.save();
        ctx.success(data);
    }
}
module.exports = new UserInfo();
